package com.Fen.aspect;

import com.Fen.annotation.AutoFill;
import com.Fen.constant.AutoFillConstant;
import com.Fen.context.BaseContext;
import com.Fen.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    //切入点
    @Pointcut("execution(* com.Fen.mapper.*.*(..)) && @annotation(com.Fen.annotation.AutoFill)")
    public void autoFillPointCut(){}

    //前置通知，在通知中进行公共字段的填充
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        log.info("自动填充公共字段");

        //获取目标方法的数据库操作方法
        MethodSignature signature =(MethodSignature)joinPoint.getSignature();
        AutoFill autoFill=signature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType = autoFill.value();

        //获取目标方法的参数
        Object[] args = joinPoint.getArgs();
        if(args.length == 0 || args[0] == null){
            return;
        }
        Object target = args[0];

        //准备赋值数据
        LocalDateTime now = LocalDateTime.now();
        Long currentUserId = BaseContext.getCurrentId();

        //赋值
        if(operationType == OperationType.INSERT){
            Method setCreateTime =target.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method setCreateUser =target.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
            Method setUpdateTime1 =target.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method setUpdateUser =target.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

            //通过反射来赋值
            setCreateTime.invoke(target, now);
            setCreateUser.invoke(target, currentUserId);
            setUpdateTime1.invoke(target, now);
            setUpdateUser.invoke(target, currentUserId);
        }else if(operationType == OperationType.UPDATE){
            Method setUpdateTime1 =target.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method setUpdateUser =target.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

            //通过反射来赋值
            setUpdateTime1.invoke(target, now);
            setUpdateUser.invoke(target, currentUserId);
        }
    }
}
